package com.sina.rd.dsp.server;

import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created with IntelliJ IDEA.
 * User: xinrong3
 * Date: 14-4-3
 * Time: 上午10:31
 */
public class RouteMap {
    private TreeMap<String,TreeMap<String,String>> map= Maps.newTreeMap();

    /**管理路由映射**/
    private ReentrantReadWriteLock routeMaplock=new ReentrantReadWriteLock();

    public String getCache(String bid,String shardid){
        routeMaplock.readLock().lock();
        String value=map.get(bid).get(shardid);
        routeMaplock.readLock().unlock();
        return value;
    }

    public HashMap<String,String> getBidCache(String tid,String shardid){
        routeMaplock.readLock().lock();
        HashMap<String,String> shardMap=Maps.newHashMap(map.get(tid));
        routeMaplock.readLock().unlock();
        return shardMap;
    }


    public boolean setCache(String bid,String shardid,String value){
        if(bid!=null&&!bid.isEmpty()&&shardid!=null&&!shardid.isEmpty()){
            routeMaplock.writeLock().lock();
            map.get(bid).put(shardid,value);
            routeMaplock.writeLock().unlock();
            return true ;
        }
        return false;
    }

    public boolean resetBidRoute(String bid,Map<String,String> shardMap){
        if(shardMap==null||shardMap.isEmpty()){
            return false;
        }
        routeMaplock.writeLock().lock();
        map.remove(bid);
        TreeMap shard=Maps.newTreeMap();
        for(Map.Entry<String,String>e:shardMap.entrySet()){
            shard.put(e.getKey(),e.getValue());
        }
        map.put(bid,shard);
        routeMaplock.writeLock().unlock();
        return true;
    }


    public boolean resetRoute(Map<String,Map<String,String>> routMap){
        if(routMap==null||routMap.isEmpty()){
            return false;
        }
        for(Map.Entry<String, Map<String, String>> e:routMap.entrySet()){
            resetBidRoute(e.getKey(),e.getValue());
        }
        return true;
    }
}
